<template>
  <a-card>
    <template #title>
      <a-form>
        <a-row :gutter="16">
          <a-col class="gutter-row" :md="6" :xs="24">
            <a-form-item label="角色名称">
              <a-input v-model:value="page.name" placeholder=""/>
            </a-form-item>
          </a-col>
          <a-col class="gutter-row" :md="6" :xs="24">
            <a-form-item label="状态">
              <a-select v-model:value="page.status" allowClear
                        :options="[{label:'启用',value:1},{label:'禁用',value:2}]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col style="text-align: right" :span="24">
            <a-button type="primary" @click="getTableData">查询</a-button>
            <a-button style="margin-left: 10px" @click="resetSearch">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </template>
    <div style="margin-bottom: 10px;text-align: right">
      <a-button type="primary" @click="addRole" v-permiss="['add']">添加角色</a-button>
    </div>
    <a-table row-key="id" :columns="tableColumn" :pagination="pagination" :data-source="tableData" :scroll="{x:1000}">
      <template #operation="{record }">
        <a-button type="link" @click="editRole(record)" v-permiss="['update']">编辑</a-button>
        <a-button type="link" @click="bindBusiness(record)" v-permiss="['businessBind']">事业部绑定</a-button>
      </template>
      <template #status="{record }">
        {{ record.status ? '开启' : '关闭' }}
      </template>
    </a-table>
    <!--    角色添加编辑-->
    <a-modal v-model:visible="visible.isShow" :title="visible.title" :afterClose="clearForm" @ok="roleConfirm"
             :maskClosable="false">
      <a-form :rules="roleRulesForm" :model="roleForm" ref="formRef" :label-col="{span:4}">
        <a-form-item label="角色名称" name="name">
          <a-input v-model:value="roleForm.name"/>
        </a-form-item>
        <a-form-item label="权限配置">
          <a-tree
              @check="checkedChange"
              ref="treeRef"
              checkable
              v-model:checkedKeys="checkedKeys"
              :tree-data="treeData"
              :replaceFields="{title:'name',key:'id'}"
          >
          </a-tree>
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-radio-group v-model:value="roleForm.status">
            <a-radio :value="1">开启</a-radio>
            <a-radio :value="2">关闭</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="备注">
          <a-textarea :rows="4" v-model:value="roleForm.remark"/>
        </a-form-item>
      </a-form>
    </a-modal>

    <!--    事业部绑定-->
    <a-modal v-model:visible="businessShow" title="事业部绑定" @ok="bindBusinessConfirm"
             :afterClose="clearBusinessList"
             :maskClosable="false">
      <a-select
          v-model:value="businessIds"
          mode="multiple"
          style="width: 100%"
          placeholder="请选择事业部"
      >
        <a-select-option v-for="item in businessList" :key="item.businessId" :value="item.businessId">
          {{ item.businessName }}
        </a-select-option>
      </a-select>
    </a-modal>
  </a-card>
</template>

<script>
import {reactive, toRefs, onMounted, ref, computed} from 'vue'
import {message, Modal} from "ant-design-vue";
import {
  fetchRoleList,
  fetchPermission,
  increaseRole,
  updateRole,
  fetchBusinessList,
  roleBusinessBind,
  updateStatus,
  fetchBindBusiness,
  fetchNationalTheater,
} from "../../../api/authority";

const tableColumn = [
  {title: '角色名称', dataIndex: 'name', width: 200, align: 'center'},
  {title: '备注', dataIndex: 'remarks', width: 200, align: 'center'},
  {title: '创建时间', dataIndex: 'createTime', width: 200, align: 'center'},
  {
    title: '状态', dataIndex: 'status', width: 200, align: 'center', slots: {customRender: 'status',}
  },
  {
    title: '操作', fixed: 'right', width: 200, align: 'center', slots: {customRender: 'operation',}
  },
]
export default {
  name: "RoleManage",
  setup() {
    const treeRef = ref(null)
    const state = reactive({
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      visible: {
        isShow: false,
        type: '',
        title: ''
      },
      roleForm: {
        status: 1
      },
      roleRulesForm: {
        name: [
          {required: true, message: '不能为空', trigger: 'blur'},
        ],
      },
      businessShow: false,
      businessList: [],
      businessIds: [],
      tableData: [],
      treeData: [],
      checkedKeys: [],
      permissionList: [],
      halfCheckKeys: [],
      parentIdArr: [],
      rows: {}
    })
    const formRef = ref(null)
    const pagination = computed(() => ({
      current: state.page.pageNum,
      total: state.page.total,
      pageSize: state.page.pageSize,
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: ['10', '50', '100', '200'],
      showTotal: total => total + '条',
      onChange: (page) => {
        state.page.pageNum = page
        method.getTableData()
      },
      onShowSizeChange: (page, size) => {
        state.page.pageNum = page
        state.page.pageSize = size
        method.getTableData()
      }
    }))
    const method = {
      async getTableData() {
        const res = await fetchRoleList(state.page)
        if (res.code === 200) {
          const {list, total} = res.data
          state.tableData = list
          state.page.total = total
        }
      },
      async getPermission(params) {
        const res = await fetchPermission(params)
        if (res.code === 200) {
          state.permissionList = res.data
          return res.data
        } else {
          return []
        }
      },
      resetSearch() {
        state.page = {
          pageNum: 1,
          pageSize: 10,
          total: 0
        }
        method.getTableData()
      },
      formatTree(list) {
        return list.filter(father => {
          const childArr = list.filter(child => father.id === child.parentId)
          if (childArr.length > 0) {
            father.children = childArr.sort((a, b) => a.orderNum - b.orderNum)
          }
          return father.parentId === 0
        }).sort((a, b) => a.orderNum - b.orderNum)
      },
      // 过滤半勾选父节点
      filterPid(list) {
        let parentIdArr = []
        const data = list.filter(father => {
          const childArr = list.filter(child => father.id === child.parentId)
          if (childArr.length) {
            const isNodeCheck = childArr.some(check => !check.checked)
            if (isNodeCheck) {
              // 子节点有一个未勾选，去除父节点勾选
              if (father.checked) {
                // 记录去除勾选的父节点id
                parentIdArr.push(father.id)
              }
              father.checked = false
            }
          }
          return true
        })
        return {
          data, parentIdArr
        }
      },
      async editRole(rows) {
        const res = await method.getPermission({userGroupId: rows.id})
        const {parentIdArr, data} = method.filterPid(res)
        state.checkedKeys = data.filter(item => item.checked).map(item => item.id)
        state.parentIdArr = parentIdArr
        state.treeData = method.formatTree(res)
        state.visible = {
          isShow: true,
          type: 'edit',
          title: '编辑角色'
        }
        state.roleForm = {
          ...rows,
          status: rows.status ? 1 : 2
        }
      },
      changeStatus({id, status}) {
        Modal.confirm({
          title: '确认进行此操作' + '?',
          async onOk() {
            const res = await updateStatus({id, status: status ? 1 : 2})
            if (res.code === 200) {
              message.success('操作成功')
              method.getTableData()
            }
          },
          class: 'test',
        });
      },
      async addRole() {
        const res = await method.getPermission()
        state.checkedKeys = res.filter(item => item.checked).map(item => item.id)
        state.treeData = method.formatTree(res)
        state.visible = {
          isShow: true,
          type: 'add',
          title: '添加菜单'
        }
      },
      checkedChange(checkedKeys, {halfCheckedKeys}) {
        state.halfCheckKeys = halfCheckedKeys
        // 删除初始记录父级id
        state.parentIdArr = []
      },
      async bindBusiness(rows) {
        const res = await fetchNationalTheater()
        if (res.code === 200) {
          const bindRes = await fetchBindBusiness({userGroupId: rows.id})
          if (bindRes.code === 200 ){
            state.rows = rows
            state.businessShow = true
            state.businessList = res.data
            state.businessIds = bindRes.data.filter(item=>item.checked).map(item=>item.businessId)
          }
        }
      },
      async bindBusinessConfirm() {
        const res = await roleBusinessBind({
          businessId: state.businessIds,
          userGroupId: state.rows.id
        })
        if (res.code === 200) {
          state.businessShow = false
          method.getTableData()
          message.success('绑定成功')

        }
      },
      clearBusinessList() {
        state.businessIds = []
      },
      async roleConfirm() {
        formRef.value.validate().then(async () => {
          const params = {
            name: state.roleForm.name,
            id: state.roleForm.id,
            remarks: state.roleForm.remarks,
            status: state.roleForm.status ? 1 : 2,
            menuId: [...state.checkedKeys, ...state.halfCheckKeys, ...state.parentIdArr]
          }
          const api = ((params) => state.visible.type === 'add' ? increaseRole(params) : updateRole(params))
          const res = await api(params)
          if (res.code === 200) {
            state.visible.isShow = false
            message.success(state.visible.type === 'add' ? '添加成功' : '编辑成功')
            method.getTableData()
          }
        })

      },
      clearForm() {
        state.roleForm = {
          status: 1
        }
        formRef.value.resetFields()
      }
    }
    onMounted(() => {
      method.getTableData()
    })
    return {
      formRef,
      treeRef,
      ...method,
      tableColumn,
      pagination,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped>

</style>
